<template>
  <div>
    <DynamicTable
      ref="dynamicTableRef"
      row-key="id"
      :header-title="$t('routes.system.system.config.appid')"
      :data-request="loadData"
      :columns="columns"
      bordered
      size="small"
      :showIndex="false"
      :fetch-config="{ listField: 'data', totalField: 'count' }"
    >
      <template #toolbar>
        <a-button v-if="canAdd" type="primary" @click="edit">
          {{ $t('common.add') }}
        </a-button>
      </template>
    </DynamicTable>
  </div>
</template>
<script lang="tsx" setup>
  import { ref } from 'vue'
  import { message } from 'ant-design-vue'
  import { DynamicTable } from '@/components/core/dynamic-table'
  import { useFormModal } from '@/hooks/useModal/useFormModal'
  import type { FormSchema } from '@/components/core/schema-form/src/types/form'
  import type { TableColumn } from '@/components/core/dynamic-table'
  import { useI18n } from '@/hooks/useI18n'
  import { ApiDescription, HttpMethod } from '@/utils/apiDescription'
  import canAccessView from '@/utils/accessCheck'
  import {
    getAppidUserList,
    addAppidUser,
    updateAppidUser,
    delAppidUser,
  } from '@/api/system/appidUser'
  import { getAllApi, getAllService } from '@/api/middleSystem'
  import dayjs from 'dayjs'
  import { formatTreeApi } from '@/utils/filters'

  defineOptions({
    name: 'Appid',
  })

  const canAdd = ref(canAccessView(new ApiDescription('/appidUser', HttpMethod.Post)))
  const canUpdate = ref(canAccessView(new ApiDescription('/appidUser/{id}', HttpMethod.Put)))
  const canDelete = ref(canAccessView(new ApiDescription('/appidUser/{id}', HttpMethod.Delete)))

  const { t } = useI18n()
  const dynamicTableRef = ref<InstanceType<typeof DynamicTable>>()

  /**
   * 表格列
   */
  const columns: TableColumn<any>[] = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: 'appid',
      dataIndex: 'appid',
      hideInSearch: true,
    },
    {
      title: 'appkey',
      dataIndex: 'appkey',
      hideInSearch: true,
    },
    {
      title: '描述',
      dataIndex: 'desc',
      hideInSearch: true,
    },
    {
      title: '到期时间',
      dataIndex: 'expiresTime',
      hideInSearch: true,
      customRender: ({ record }) => {
        return dayjs(record.expiresTime).format('YYYY-MM-DD HH:mm:ss')
      },
    },
    {
      title: '操作',
      dataIndex: 'ACTION',
      hideInSearch: true,
      actions: ({ record }) => [
        {
          label: t('common.edit'),
          hide: !canUpdate.value,
          onClick: () => edit(record),
        },
        {
          label: t('common.delete'),
          danger: true,
          hide: !canDelete.value,
          popConfirm: {
            title: t('column.confirmDel'),
            onConfirm: () => del(record),
          },
        },
      ],
    },
  ]

  /**
   * 加载数据
   */
  const loadData = async params => {
    const { name, pageIndex, pageSize } = params
    const data = await getAppidUserList({ page: pageIndex, pageSize: pageSize, name: name })
    return data
  }

  const [showModal] = useFormModal()
  const formSchemas: FormSchema[] = [
    {
      field: 'name',
      component: 'Input',
      label: '名称',
      rules: [{ required: true }],
    },
    {
      field: 'appid',
      component: 'Input',
      label: 'appid',
      rules: [{ required: true }],
    },
    {
      field: 'appkey',
      component: 'Input',
      label: 'appkey',
      rules: [{ required: true }],
    },
    {
      field: 'desc',
      component: 'Input',
      label: '描述',
      rules: [{ required: true }],
    },
    {
      field: 'expiresTime',
      component: 'DatePicker',
      label: '到期时间',
      rules: [{ required: true }],
      componentProps: {
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      field: 'apis',
      component: 'Tree',
      label: '权限分配',
      componentProps: {
        defaultExpandAll: true,
        checkable: true,
        multiple: true,
        vModelKey: 'checkedKeys',
        fieldNames: { children: 'children', title: 'name', key: 'id' },
      },
    },
  ]

  function extractItemsByIds(tree, ids) {
    let result: any = []
    function traverse(node) {
      if (ids.includes(node.id) && !node.children) {
        result.push(node)
      }
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => traverse(child))
      }
    }
    tree.forEach(rootNode => traverse(rootNode))
    return result
  }

  /**
   * 打开新增/编辑弹窗
   */
  const edit = async record => {
    const { data: apiData } = await getAllApi()
    const apiList = apiData
    const treeData = formatTreeApi(apiData)
    const { data: serviceData } = await getAllService(1, 100000, '')
    serviceData.push({ appId: 'middleSystem', name: '中台服务', children: [] })
    serviceData.forEach((item: any) => {
      item.id = item.appId ? item.appId : 'middleSystem'
      item.children = []
      treeData.forEach((value: any) => {
        if (item.appId == value.children[0].appId) item.children.push(value)
        if (!value.children[0].appId && item.id == 'middleSystem') item.children.push(value)
      })
    })

    const [formRef] = await showModal({
      modalProps: {
        title: `${record.id ? t('common.edit') : t('common.add')}`,
        width: '40%',
        onFinish: async values => {
          let { name, appid, appkey, desc, expiresTime, apis } = values
          let filteredItems = apis?.length ? extractItemsByIds(treeData, apis) : []
          if (record.id) {
            await updateAppidUser(record.id, {
              name: name,
              appid: appid,
              appkey: appkey,
              desc: desc,
              expiresTime: expiresTime,
              apis: filteredItems,
            })
          } else {
            await addAppidUser({
              name: name,
              appid: appid,
              appkey: appkey,
              desc: desc,
              expiresTime: expiresTime,
              apis: filteredItems,
            })
          }
          message.success('操作成功')
          dynamicTableRef.value?.reload()
        },
      },
      formProps: {
        labelWidth: 100,
        layout: 'horizontal',
        schemas: formSchemas,
      },
    })

    formRef?.updateSchema([
      {
        field: 'apis',
        componentProps: { treeData: serviceData },
      },
    ])

    if (record.id) {
      let apis: any = []
      apiList.forEach((i: any) => {
        record.apis.forEach((o: any) => {
          if (i.url === o.url && i.method === o.method) {
            apis.push(i.id)
          }
        })
      })
      formRef?.setFieldsValue({
        name: record.name,
        appid: record.appid,
        appkey: record.appkey,
        desc: record.desc,
        expiresTime: record.expiresTime,
        apis: apis,
      })
    }
  }

  /**
   * 删除
   */
  const del = async record => {
    await delAppidUser(record.id)
    message.success('操作成功')
    dynamicTableRef.value?.reload()
  }
</script>
